package org.numb.concurrency.chapter02;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;

public class InterruptedThread extends Thread {

    @Override
    public void run() {
        try (ServerSocket server = new ServerSocket(8080)) {
            // 如果不被interrupted，则一直尝试socket连接
            while (!isInterrupted()) {
                // 调用accept(), 线程阻塞，设置最大阻塞时间为5秒
                server.setSoTimeout(5 * 1000);
                try {
                    Socket accept = server.accept();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(accept.getInputStream()));
                    System.out.println(reader.readLine());
                    reader.close();
                } catch (SocketTimeoutException e) {
                    System.out.println("连接超时...");
                }

            }
            System.out.println("调用interrupt(), 退出线程...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new InterruptedThread();
        thread.start();
        Thread.sleep(3 * 1000);
        thread.interrupt();
    }
}
